import { app, BrowserWindow, ipcMain, IpcMainEvent } from "electron";
import * as path from "node:path";
import * as url from "node:url";
import addon from "./addon";
// import addon from '../addon';
// 注释掉无法找到的模块导入
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//、、 @ts-expect-error
// import addon from './assets/hello.node';

// import * as path from "node:path";
// // @ts-expect-error
// import addon from path.join(__dirname, '../assets/hello.node');

// let addon: any;

// try {
//   const addonPath = path.join(__dirname, './assets/hello.node');
//   console.log('test:zuoyu:path', addonPath);
//   process.dlopen(module, addonPath);
//   addon = module.exports;
//   console.log('addon 加载成功:', addon);
// } catch (error) {
//   console.error('加载 addon 失败:', error);
// }

const isEnvSet = "ELECTRON_IS_DEV" in process.env;
const getFromEnv = Number.parseInt(process.env.ELECTRON_IS_DEV as string, 10) === 1;
const isDev = isEnvSet ? getFromEnv : !app.isPackaged;

let mainWindow: BrowserWindow | null;

const createWindow = () => {
  mainWindow = new BrowserWindow({
    show: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: path.join(__dirname, "preload.js"),
    } as Electron.WebPreferences,
  });

  ipcMain.on("HelloWorld", async (_: IpcMainEvent, __: any[]) => {
    mainWindow?.webContents.send("HelloWorld", { message: "Hello World" });
  });

  // 设置 IPC 处理程序
  ipcMain.handle('callHello', () => {
    console.log('test:zuoyu:handle', Object.getOwnPropertyNames(addon));
    // return addon.hello();
    if (addon && typeof addon.hello === 'function') {
      return addon.hello();
    } else {
      console.error('addon 或 hello 方法未找到', addon);
      return '错误：addon 或 hello 方法未定义';
    }
  });

  mainWindow.loadURL(
    isDev
      ? "http://localhost:3000/"
      : url.format({
          pathname: path.join(__dirname, "./index.html"),
          protocol: "file:",
          slashes: true,
        })
  );

  isDev && mainWindow.webContents.openDevTools();
  !isDev && mainWindow.removeMenu();

  mainWindow.on("closed", () => {
    mainWindow = null;
  });

  mainWindow.maximize();
  mainWindow.show();
};

app.on("ready", () => {
  createWindow();
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

app.on("activate", () => {
  if (mainWindow === null) createWindow();
});
